<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="表名称" min-width="100" prop="busTableName">
        <el-input
          v-model="queryParams.busTableName"
          placeholder="请输入业务表名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="表描述" min-width="100" prop="busTableComment">
        <el-input
          v-model="queryParams.busTableComment"
          placeholder="请输入表描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="表类型" prop="tableType">
        <el-select v-model="queryParams.tableType" placeholder="请选择表类型" clearable size="small">
          <el-option
            v-for="dict in tableTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="表状态" prop="tableStatus">
        <el-select v-model="queryParams.tableStatus" placeholder="请选择表状态" clearable size="small">
          <el-option
            v-for="dict in tableStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
		      plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bus:table:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
		      plain
          icon="el-icon-edit"
          size="mini"
          @click="handleTest"
          v-hasPermi="['bus:table:edit']"
        >测试</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
		      plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bus:table:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['bus:table:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
		      plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bus:table:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-refresh"
          v-loading.fullscreen.lock="fullscreenLoading"
          :disabled="single"
          @click="handleInitTable"
        >初始化表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          icon="el-icon-refresh"
          :disabled="single"
          @click="handelBackInitTable"
        >反初始化表</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="tableList" ref="multipleTable"
              @selection-change="handleSelectionChange" @select="select"
              :row-class-name="tabRowClassName" @row-click="selectThisRow" :height="this.tableHeight">
      <el-table-column type="selection" min-width="20" align="center" />
      <el-table-column label="数据源名" align="center" min-width="50" prop="dbName" />
      <el-table-column label="表名称" align="center" min-width="50" prop="busTableName" />
      <el-table-column label="表描述" align="center" min-width="50" prop="busTableComment" />
      <el-table-column label="api编码" align="center" min-width="50" prop="syncApiCode" />
      <el-table-column label="表类型" align="center" min-width="30" prop="tableType" :formatter="tableTypeFormat" />
      <el-table-column label="表状态" align="center" min-width="30" prop="tableStatus" :formatter="tableStatusFormat" />
      <el-table-column label="初始化时间" align="center" min-width="50" prop="updateTime" />
      <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            v-loading.fullscreen.lock="fullscreenLoading"
            @click="handleSyncJg(scope.row)"
          >同步结构</el-button>
          <!--<el-button-->
            <!--icon="el-icon-view"-->
            <!--size="mini"-->
            <!--type="text"-->
            <!--@click="preview(scope.row)"-->
            <!--v-hasPermi="['bus:table:preview']"-->
          <!--&gt;预览</el-button>-->

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEditTable(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bus:table:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的业务表
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <preview ref="import" @ok="handleQuery" />
  </div>
</template>

<script>
import { listTable, getTables, delTable, addTable, updateTable,syncTableJg,initTable,backInitTable,previewTable,test } from "@/api/datafactory/table";
import { getToken } from "@/utils/auth";
import  preview  from "./preview";
export default {
  name: "Table",
  components: {preview
  },
  data() {
    return {
      //
      // 遮罩层
      loading: true,
      // 全屏遮罩
      fullscreenLoading: false,
      // 选中数组
      ids: [],
      tableNames: [],
      tableStatus:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代码生成业务表格数据
      tableList: [],
      // 表类型数据
      tableTypeOptions: [],
      tableStatusOptions: [],
      syncApiOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（）
        open: false,
        // 弹出层标题（）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/datafactory/table/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        busTableName: null,
        busTableComment: null,
        syncApiCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("table_type").then(response => {
      this.tableTypeOptions = response.data;
    });
    this.getDicts("table_status").then(response => {
      this.tableStatusOptions = response.data;
  });
    this.tableHeight = (document.body.offsetHeight)-270
    /*var query = {"appName":"kingdee"};
    this.getSyncApi(query).then(response => {
      this.syncApiOptions = response.data;
    });*/
  },
  methods: {
    /** 更改斑马纹 */
    tabRowClassName({row,rowIndex}){
      let index = rowIndex + 1;
      if(index %2 == 0){
        return 'two-color'
      }else {
        return "one-color"
      }
    },
    selectThisRow(row){
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    /** 查询代码生成业务列表 */
    getList() {
      this.loading = true;
      listTable(this.queryParams).then(response => {
        this.tableList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    tableTypeFormat(row, column) {
      return this.selectDictLabel(this.tableTypeOptions, row.tableType);
    },
    tableStatusFormat(row, column) {
      return this.selectDictLabel(this.tableStatusOptions, row.tableStatus);
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tableId: null,
        busTableName: null,
        busTableComment: null,
        syncApiCode: null,
        busGroupName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tableId)
      this.tableStatus=selection.map(item => item.tableStatus)
      this.tableNames = selection.map(item => item.tableName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    select(ids) {
      if (ids.length > 1) {
        let deleteRow = ids.shift()
        this.$refs.multipleTable.toggleRowSelection(deleteRow, false)
        ids.length = 1
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加业务表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const tableId = row.tableId || this.ids
      getTables(tableId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改业务表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.tableId != null) {
            updateTable(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTable(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 打开预览表弹窗 */
    preview(row) {
      console.log(row)
      this.$refs.import.show(row);
    },
    /** 同步表结构操作 */
    handleSyncJg(row) {
      const tableName = row.busTableComment;
      const tableType = row.tableType;
      console.log(tableType);
      const models = ['base', 'bill','report'];
      if(models.indexOf(row.tableType)<0){
        this.msgInfo("该表类型不支持同步表结构");
        return;
      }
      this.$confirm('确认要同步"' + tableName + '"表结构吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.fullscreenLoading  = false;
        return syncTableJg(row).then(() =>{
          this.fullscreenLoading  = false;
        })
      }).then(() => {
        this.fullscreenLoading  = false;
        this.msgSuccess("同步成功");
      })

    },
    /** 初始化表结构操作 */
    handleInitTable() {
      const ids =  this.ids[0];
      this.$confirm('确认要强制初始化【 ' + ids + ' 】表数据吗？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
          return initTable(ids);
      }).then(() => {
        this.msgSuccess("初始化成功");
        this.getList();
      })
    },
    /** 反初始化表结构操作 */
    handelBackInitTable(){
      let tableStatus = this.tableStatus[0];
      if(tableStatus===0){
        this.msgError("已是未初始化状态，不可反初始化")
      }else {
        const ids =  this.ids[0];
        this.$confirm('确认要反初始化【 ' + ids + ' 】表数据吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return backInitTable(ids);
        }).then(() => {
          this.msgSuccess("反初始化成功");
          this.getList();
        })
      }

    },
    handleTest(){
      test().then(response => {
        this.msgSuccess("测试成功");
      })
    },

    /** 修改按钮操作 */
    handleEditTable(row) {
      const tableId = row.tableId || this.ids[0];
      this.$router.push("/bus/editTable/" + tableId);
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const tableIds = row.tableId || this.ids;
      this.$confirm('是否确认删除业务表为【 ' + tableIds + ' 】的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          delTable(tableIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否导出表', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
      }).then(() => {
        this.download('datafactory/table/export', {
          ...this.queryParams
        }, `table_${new Date().getTime()}.xlsx`)
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "表导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('datafactory/table/importTemplate', {
        ...this.queryParams
      }, `table_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
